package com.attilax.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;


import log.Log;

//import com.attilax.core;
import com.attilax.exception.ExUtil;
import com.attilax.sync.AsyncUtil;


public class SocketUtil {
	//Socket ssocket = null;
//	Socket client_socket = null;
	public Socket socket = null;
	
	public Log logger=new Log();

	public SocketUtil(Socket socket2) {
		socket = socket2;
	}

	public SocketUtil() {
		// TODO Auto-generated constructor stub
	}

	public SocketUtil rawSocketUtil;

	public SocketUtil(SocketUtil client_SocketUtil) {
		rawSocketUtil = client_SocketUtil;
	}

	public SocketUtil pipe(InputStream cis, InputStream sis, OutputStream sos,
			OutputStream cos) {
		try {
			int length;
			int BUFSIZ = 10024; // 缓冲区最大字节数
			byte bytes[] = new byte[BUFSIZ];
			AsyncUtil syncUtil1 = new AsyncUtil();
			Runnable runnable = new Runnable() {
				public void run() {
					while (true) {
						int length;
						try {

							if ((length = sis.read(bytes)) > 0) {
								cos.write(bytes, 0, length);
								 if (logger!=null)
									 logger. writeLog(bytes, 0, length, false);
							} else if (length < 0)
								break;

						} catch (SocketTimeoutException e) {
							ExUtil.throwEx(e);
						} catch (InterruptedIOException e) {
							System.out.println("\nResponse Exception:");
							e.printStackTrace();
							ExUtil.throwEx(e);

						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							ExUtil.throwEx(e);
						}
					}

				}
			};
	//		syncUtil1.execMeth_Ays(runnable, "threadName:sis2cos");

			while (true) {
				try {
					if ((length = cis.read(bytes)) > 0) {
						sos.write(bytes, 0, length);
						 if (logger!=null)
							 logger. writeLog(bytes, 0, length, true);
					} else if (length < 0)
						break;
				} catch (SocketTimeoutException e) {
					ExUtil.throwEx(e);
				} catch (InterruptedIOException e) {
					System.out.println("\nRequest Exception:");
					e.printStackTrace();
				}
				//threadName:sis2cos
				try {

					if ((length = sis.read(bytes)) > 0) {
						cos.write(bytes, 0, length);
						// if (logging)
						// writeLog(bytes, 0, length, false);
					} else if (length < 0)
						break;

				} catch (SocketTimeoutException e) {
					ExUtil.throwEx(e);
				} catch (InterruptedIOException e) {
					System.out.println("\nResponse Exception:");
					e.printStackTrace();
					ExUtil.throwEx(e);

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					ExUtil.throwEx(e);
				}

			}
		} catch (Exception e0) {
			System.out.println("Pipe异常: " + e0);
			ExUtil.throwEx(e0);
		}
		return this;
	}

	public SocketUtil createConn2remote(String host, int port, int retry,
			int CONNECT_PAUSE) {

		// int retry = CONNECT_RETRIES;
		while (retry-- != 0) {
			try {
				socket = new Socket(host, port); // 尝试建立与目标主机的连接
				// Socket[addr=s.cimg.163.com/124.232.128.11,port=80,localport=61079]

				break;
			} catch (Exception e) {

			}
			// 等待
			try {
				Thread.sleep(CONNECT_PAUSE);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (socket == null)
			throw new RuntimeException(" socket is null,create conn fail");
		return this;
	}

	public String firstLine = "";
	public  int charFirstLineBreak;
	public SocketUtil readFirstLine(InputStream cis) {
		// String buffer="";

		//
		// try {
		while (true) {
			int c;
			try {
				c = cis.read();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				throw new RuntimeException("read err:now read line is:"
						+ firstLine, e);
			}

			// catch (SocketTimeoutException e) {
			// throw new RuntimeException("SocketTimeoutException", e);
			// }
			if (c == -1)
				break; // -1为结尾标志
			if (c == '\r' || c == '\n') {
				if (logger != null) {
					logger.writeLog(c, true);
					logger.flush();
				}
				charFirstLineBreak=c;
				break;// 读入第一行数据
			}

			firstLine = firstLine + (char) c;
			if (logger != null) {
				logger.writeLog(c, true);
				logger.flush();
			}
		}

		return this;
	}

	public SocketUtil close(Object ssocket) {
		if (ssocket instanceof Socket) {
			try {
				((Socket) ssocket).close();
			} catch (IOException e) {
				System.out.println("\n Socket Closed Exception:");
				e.printStackTrace();
			}

		}
		if (ssocket instanceof InputStream) {
			try {
				((InputStream) ssocket).close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (ssocket instanceof OutputStream) {
			try {
				((OutputStream) ssocket).close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return this;
	}

	public SocketUtil setSoTimeout(int tIMEOUT) {
		try {
			socket.setSoTimeout(tIMEOUT);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}

		return this;
	}

	// cis为客户端输入流，sis为目标主机输入流
	public InputStream is = null;
	// cos为客户端输出流，sos为目标主机输出流
	public OutputStream os = null;

	public SocketUtil write(String reqHead_firstLine) {

		try {
			if (is == null)
				is = socket.getInputStream();
			if (os == null)
				os = socket.getOutputStream();
			os.write(reqHead_firstLine.getBytes()); // 将请求头写入
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return this;
	}

	public SocketUtil readFirstLine() {
		try {
			if (is == null)

				is = socket.getInputStream();

			if (os == null)
				os = socket.getOutputStream();
			return this.readFirstLine(is);
		} catch (IOException e) {

			// e.printStackTrace();
			ExUtil.throwEx(e);
		}
		return this;
	}

	public SocketUtil pipe(InputStream cis, OutputStream cos) {
		pipe(cis, this.is, this.os, cos);
		return this;
	}

	public void close() {
		try {
			if (this.socket != null)
				this.close(this.socket);
			if (this.is != null)
				this.close(this.is);
			if (this.os != null)
				this.close(this.os);
			if (this.rawSocketUtil != null)
				rawSocketUtil.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public SocketUtil setLogger(Log logger2) {
		this.logger=logger2;
		return this;
	}

	public SocketUtil write(int charFirstLineBreak2) {
		try {
			if (is == null)
				is = socket.getInputStream();
			if (os == null)
				os = socket.getOutputStream();
			os.write(charFirstLineBreak2); // 将请求头写入
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return this;
	}

}
